#include <stdio.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "hi_io.h"
#include "iot_pwm.h"
#include "hi_pwm.h"
#include "hi_time.h"

// 呼吸灯PWM初始化
static void breathingLedInit()
{
    hi_gpio_init();
    hi_io_set_func(HI_IO_NAME_GPIO_10, HI_IO_FUNC_GPIO_10_PWM1_OUT);
    hi_io_set_pull(HI_IO_NAME_GPIO_10, HI_IO_PULL_UP);
    hi_pwm_init(HI_PWM_PORT_PWM1);
    hi_pwm_set_clock(PWM_CLK_XTAL);
}

// 呼吸灯任务
static void breathingLedTask(void *arg)
{
    breathingLedInit();
    uint16_t dutyCycle;
    int step = 10;
    while (1) {
        // 逐渐变亮
        for (dutyCycle = 0; dutyCycle <= 1000; dutyCycle += step) {
            hi_pwm_start(HI_PWM_PORT_PWM1, dutyCycle, 1000);
            hi_udelay(10000);
        }
        // 逐渐变暗
        for (dutyCycle = 1000; dutyCycle > 0; dutyCycle -= step) {
            hi_pwm_start(HI_PWM_PORT_PWM1, dutyCycle, 1000);
            hi_udelay(10000);
        }
    }
}

// 创建线程处理呼吸灯任务
static void LedEntry(void)
{
    osThreadAttr_t attr = {0};
    attr.name = "breathingLedTask";
    attr.stack_size = 4096 * 2;
    attr.priority = osPriorityNormal;
    if (osThreadNew(breathingLedTask, NULL, &attr) == NULL)
    {
        printf("[LedEntry] create breathingLedTask failed!\n");
    }
}
SYS_RUN(LedEntry);